<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>如何设计一个任务管理器 | 被删的前端游乐场</title>
    <meta name="generator" content="VuePress 1.8.2">
    
    <meta name="description" content="Just playing around">
    
    <link rel="preload" href="/front-end-playground/assets/css/0.styles.6ad2a9ca.css" as="style"><link rel="preload" href="/front-end-playground/assets/js/app.1e2670bf.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/2.38d016d1.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/3.e3f029cb.js" as="script"><link rel="preload" href="/front-end-playground/assets/js/36.be11f947.js" as="script">
    <link rel="stylesheet" href="/front-end-playground/assets/css/0.styles.6ad2a9ca.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/front-end-playground/" class="home-link router-link-active"><!----> <span class="site-name">被删的前端游乐场</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/front-end-playground/" class="nav-link">概述</a></div><div class="nav-item"><a href="/front-end-playground/front-end-basic/" class="nav-link router-link-active">前端领域</a></div><div class="nav-item"><a href="/front-end-playground/vue/" class="nav-link">Vue学习</a></div><div class="nav-item"><a href="/front-end-playground/wxapp/" class="nav-link">小程序学习</a></div><div class="nav-item"><a href="/front-end-playground/front-end-others/" class="nav-link">百家齐放</a></div><div class="nav-item"><a href="/front-end-playground/front-end-addon/" class="nav-link">前端的进击</a></div><div class="nav-item"><a href="/front-end-playground/front-end-work/" class="nav-link">前端与工作</a></div><div class="nav-item"><a href="/front-end-playground/faq.html" class="nav-link">FAQ</a></div> <a href="https://github.com/godbasin/front-end-playground" target="_blank" rel="noopener noreferrer" class="repo-link">
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/front-end-playground/" class="nav-link">概述</a></div><div class="nav-item"><a href="/front-end-playground/front-end-basic/" class="nav-link router-link-active">前端领域</a></div><div class="nav-item"><a href="/front-end-playground/vue/" class="nav-link">Vue学习</a></div><div class="nav-item"><a href="/front-end-playground/wxapp/" class="nav-link">小程序学习</a></div><div class="nav-item"><a href="/front-end-playground/front-end-others/" class="nav-link">百家齐放</a></div><div class="nav-item"><a href="/front-end-playground/front-end-addon/" class="nav-link">前端的进击</a></div><div class="nav-item"><a href="/front-end-playground/front-end-work/" class="nav-link">前端与工作</a></div><div class="nav-item"><a href="/front-end-playground/faq.html" class="nav-link">FAQ</a></div> <a href="https://github.com/godbasin/front-end-playground" target="_blank" rel="noopener noreferrer" class="repo-link">
    Github
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0" style="padding-top:10px;"><div class="kitty-main" data-v-2b653b36><span class="stand" data-v-2b653b36></span> <div class="cat" data-v-2b653b36><div class="body" data-v-2b653b36></div> <div class="head" data-v-2b653b36><div class="ear" data-v-2b653b36></div> <div class="ear" data-v-2b653b36></div></div> <div class="face" data-v-2b653b36><div class="nose" data-v-2b653b36></div> <div class="whisker-container" data-v-2b653b36><div class="whisker" data-v-2b653b36></div> <div class="whisker" data-v-2b653b36></div></div> <div class="whisker-container" data-v-2b653b36><div class="whisker" data-v-2b653b36></div> <div class="whisker" data-v-2b653b36></div></div></div> <div class="tail-container" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36><div class="tail" data-v-2b653b36></div></div></div></div></div></div></div></div></div></div> <p class="sidebar-heading open"><span>前端架构</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/front-end-playground/front-end-basic/deep-learning/module-seperate.html" class="sidebar-link">谈谈依赖和解耦</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/trace-stash.html" class="sidebar-link">大型前端项目要怎么跟踪和分析函数调用链</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/build-application.html" class="sidebar-link">前端构建大型应用</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/reactive-programing.html" class="sidebar-link">响应式编程在前端领域的应用</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/vscode-event.html" class="sidebar-link">VSCode 源码解读：事件系统设计</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/vscode-ipc.html" class="sidebar-link">VSCode 源码解读：IPC通信机制</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/online-doc-network.html" class="sidebar-link">在线文档的网络层设计思考</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/front-end-performance-analyze.html" class="sidebar-link">补齐Web前端性能分析的工具盲点</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/monitor-and-report.html" class="sidebar-link">前端监控体系搭建</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/why-spreadsheet-app-excited.html" class="sidebar-link">在线Excel项目到底有多刺激</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/task-runner-design.html" aria-current="page" class="active sidebar-link">如何设计一个任务管理器</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/front-end-playground/front-end-basic/deep-learning/task-runner-design.html#单个任务的设计" class="sidebar-link">单个任务的设计</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/front-end-basic/deep-learning/task-runner-design.html#任务管理器" class="sidebar-link">任务管理器</a></li><li class="sidebar-sub-header"><a href="/front-end-playground/front-end-basic/deep-learning/task-runner-design.html#结束语" class="sidebar-link">结束语</a></li></ul></li><li><a href="/front-end-playground/front-end-basic/deep-learning/network-design-responsibility-driven-design.html" class="sidebar-link">在线文档的网络层开发思考--职责驱动设计</a></li><li><a href="/front-end-playground/front-end-basic/deep-learning/network-design-dependency-decoupling.html" class="sidebar-link">在线文档的网络层开发思考--依赖关系梳理</a></li></ul></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>前端深入理解</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0" style="padding-top:;"><!----> <p class="sidebar-heading"><span>前端入门</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><p>一般来说，我们在遇到对顺序要求严格的任务执行时，就需要维护一个任务管理器，保证任务的执行顺序。前端开发过程中，设计队列/栈的场景比较多，而需要用到任务管理器的场景偏少，本文主要介绍如何实现一个任务管理器。</p> <p>理解任务管理器比较好的场景大概是协同文档编辑的场景，比如 Google Docs、腾讯文档、Sketch 协同等。我们在进行协同编辑的时候，对版本和消息时序有比较严格的要求，因此常常需要维护一个任务管理器来管理版本相关的任务。</p> <p>以上是一些科普知识，用于辅助大家理解接下来的任务管理器设计，下面我们来进入正文。</p> <h2 id="单个任务的设计"><a href="#单个任务的设计" class="header-anchor">#</a> 单个任务的设计</h2> <p>对于单个任务的设计，主要考虑任务的执行。一个任务的作用就是用来运行的，那么对于任务来说，可能会有几个状态：待执行、正在执行、执行失败、执行成功等：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">enum</span> <span class="token constant">TASK_STATUS</span> <span class="token punctuation">{</span>
  <span class="token constant">INIT</span> <span class="token operator">=</span> <span class="token string">&quot;INIT&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 初始状态</span>
  <span class="token constant">READY</span> <span class="token operator">=</span> <span class="token string">&quot;READY&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 可执行</span>
  <span class="token constant">RUNNING</span> <span class="token operator">=</span> <span class="token string">&quot;RUNNING&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 执行中</span>
  <span class="token constant">SUCCESS</span> <span class="token operator">=</span> <span class="token string">&quot;SUCCESS&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 执行成功</span>
  <span class="token constant">FAILED</span> <span class="token operator">=</span> <span class="token string">&quot;FAILED&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 执行失败</span>
  <span class="token constant">DESTROY</span> <span class="token operator">=</span> <span class="token string">&quot;DESTROY&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 已销毁</span>
<span class="token punctuation">}</span>
</code></pre></div><h3 id="生命周期"><a href="#生命周期" class="header-anchor">#</a> 生命周期</h3> <p>既然涉及到任务的各个状态，我们也可以赋予任务一些生命周期。这里我们举一些例子，但最终的生命周期设计应该要和自己业务实际情况结合。</p> <p><strong>onReady: 任务执行前准备工作</strong></p> <p>在每个任务执行之前，我们都需要再次确认下这个任务的状态（是否已经失效），也可能需要做些准备工作，这个阶段可以命名为<code>onReady</code>：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">export</span> <span class="token keyword">interface</span> <span class="token class-name">ICommonTask</span> <span class="token punctuation">{</span>
  <span class="token function">onReady</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span><span class="token builtin">boolean</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>可以看到，该生命周期以返回 Promise 的方式来运行，该 Promise 包括一个布尔值，用于判断任务是否继续执行。比如我们需要在执行任务之前，从服务端获取一些数据，那么可以这么实现：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">class</span> <span class="token class-name">ATask</span> <span class="token keyword">implements</span> <span class="token class-name">ICommonTask</span> <span class="token punctuation">{</span>
  <span class="token keyword">async</span> <span class="token function">onReady</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">const</span> result <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token function">getSomeDate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>result<span class="token punctuation">.</span>isSuccess<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p><strong>onRun: 任务执行中</strong></p> <p>任务准备工作完成之后，任务就需要开始真正运行了。同样的，我们将这个阶段命名为<code>onRun</code>：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">export</span> <span class="token keyword">interface</span> <span class="token class-name">ICommonTask</span> <span class="token punctuation">{</span>
  <span class="token function">onReady</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span><span class="token builtin">boolean</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
  <span class="token function">onRun</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span>CommonTask<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">|</span> <span class="token keyword">void</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这里我们看到，<code>onRun</code>阶段执行同样返回一个 Promise，但 Promise 内容和<code>onReady</code>阶段不一致，它可能返回一个或者多个<code>CommonTask</code>组成的数组。这是因为一个任务执行的过程中，可能会产生新的任务，也可能由于其他条件限制，导致它需要创建一个别的任务先执行完毕，才能继续执行自己原本的任务。比如，B 任务在执行的时候，如果条件不满足，则需要先执行一个 A 任务：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">class</span> <span class="token class-name">BTask</span> <span class="token keyword">implements</span> <span class="token class-name">ICommonTask</span> <span class="token punctuation">{</span>
  <span class="token comment">// 其他省略</span>
  <span class="token keyword">async</span> <span class="token function">onRun</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>needATask<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span> <span class="token punctuation">[</span><span class="token keyword">new</span> <span class="token class-name">ATask</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">resetTask</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">// 其他正常执行任务逻辑</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p><strong>onDestroy: 任务执行完毕，即将销毁</strong></p> <p>很多时候我们实现一些模块功能，都会产生一些临时变量，也可能有一些事件绑定、DOM 元素需要在该模块注销的时候清除，因此进行主动的销毁和清理是一个很好的习惯。对于一个任务的执行来说也是一样的，我们将这个阶段命名为<code>onDestroy</code>：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">export</span> <span class="token keyword">interface</span> <span class="token class-name">ICommonTask</span> <span class="token punctuation">{</span>
  <span class="token function">onReady</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span><span class="token builtin">boolean</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
  <span class="token function">onRun</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span>CommonTask<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">|</span> <span class="token keyword">void</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
  <span class="token function">onDestroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span><span class="token keyword">void</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>对于任务的生命周期相关，我们暂时讲到这里，接下来我们来看任务的执行。</p> <h3 id="任务执行"><a href="#任务执行" class="header-anchor">#</a> 任务执行</h3> <p>由于每个任务都会有状态、生命周期、执行功能、重置功能，我们可以实现一个通用的任务：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">abstract</span> <span class="token keyword">class</span> <span class="token class-name">CommonTask</span> <span class="token keyword">implements</span> <span class="token class-name">ICommonTask</span> <span class="token punctuation">{</span>
  <span class="token comment">/** 生命周期钩子 **/</span>
  <span class="token keyword">abstract</span> <span class="token function-variable function">onReady</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span><span class="token builtin">boolean</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
  <span class="token keyword">abstract</span> <span class="token function-variable function">onRun</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span>CommonTask<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">|</span> <span class="token keyword">void</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>
  <span class="token keyword">abstract</span> <span class="token function-variable function">onDestroy</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span><span class="token keyword">void</span><span class="token operator">&gt;</span><span class="token punctuation">;</span>

  <span class="token comment">/** 执行任务 **/</span>
  <span class="token keyword">public</span> <span class="token keyword">async</span> <span class="token function">execute</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Promise</span><span class="token operator">&lt;</span>CommonTask<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">|</span> <span class="token keyword">void</span><span class="token operator">&gt;</span> <span class="token punctuation">{</span>
    <span class="token comment">// step 1 准备任务</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token punctuation">(</span><span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">onReady</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 任务准备校验不通过，直接没必要执行了</span>
      <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">onDestroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">// step 2 执行任务</span>
    <span class="token keyword">const</span> runResult <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">onRun</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>runResult<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 若分裂出新的任务，返回并不再继续执行了</span>
      <span class="token keyword">return</span> runResult<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token comment">// step 3 销毁任务</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">onDestroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这里 CommonTask 提供了一个通用的<code>execute</code>方法用于执行任务，我们能看到其中的实现也是根据生命周期依次执行。当然，这里其实还需要在执行到对应生命周期的时候，扭转任务状态。除此之外，任务执行异常的处理也并不在这里，因此外界需要进行<code>try catch</code>处理。</p> <p>那么到底在哪里需要进行异常处理呢？我们接下来看看任务管理器。</p> <h2 id="任务管理器"><a href="#任务管理器" class="header-anchor">#</a> 任务管理器</h2> <p>显然，任务管理器的职责主要是保证任务队列中的任务有序、顺利地执行，其中会包括任务执行时的异常处理。除此之外，任务管理器还需要对外提供添加任务，以及暂停、恢复、停止这样的能力。</p> <h3 id="任务管理器状态"><a href="#任务管理器状态" class="header-anchor">#</a> 任务管理器状态</h3> <p>既然任务管理器有对任务的管理，当然它也需要维护自身的状态，例如：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">enum</span> <span class="token constant">QUEUE_STATUS</span> <span class="token punctuation">{</span>
  <span class="token constant">WORKING</span> <span class="token operator">=</span> <span class="token string">&quot;WORKING&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 工作中</span>
  <span class="token constant">PAUSE</span> <span class="token operator">=</span> <span class="token string">&quot;PAUSE&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 暂停</span>
  <span class="token constant">IDLE</span> <span class="token operator">=</span> <span class="token string">&quot;IDLE&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 空闲</span>
  <span class="token constant">SHUTDOWN</span> <span class="token operator">=</span> <span class="token string">&quot;SHUTDOWN&quot;</span><span class="token punctuation">,</span> <span class="token comment">// 关停</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这些是任务管理器基本的状态，包括空闲状态、工作中、暂停、停止等。对于每一个不同的状态来说，相应的任务管理器也会有一些更新状态的方法：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">class</span> <span class="token class-name">TaskManager</span> <span class="token punctuation">{</span>
  status<span class="token operator">:</span> <span class="token constant">QUEUE_STATUS</span> <span class="token operator">=</span> <span class="token constant">QUEUE_STATUS</span><span class="token punctuation">.</span><span class="token constant">IDLE</span><span class="token punctuation">;</span>
  <span class="token comment">// 暂停任务管理器</span>
  <span class="token keyword">public</span> <span class="token function">pause</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>status <span class="token operator">=</span> <span class="token constant">QUEUE_STATUS</span><span class="token punctuation">.</span><span class="token constant">PAUSE</span><span class="token punctuation">;</span>
    <span class="token comment">// 当前正在运行的任务需要处理</span>
  <span class="token punctuation">}</span>
  <span class="token comment">// 恢复任务管理器</span>
  <span class="token keyword">public</span> <span class="token function">resume</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 如果被关停了，则不能恢复啦</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>isShutDown<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">return</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>status <span class="token operator">=</span> <span class="token constant">QUEUE_STATUS</span><span class="token punctuation">.</span><span class="token constant">WORKING</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">work</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token comment">// 关停任务管理器</span>
  <span class="token keyword">public</span> <span class="token function">resume</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>status <span class="token operator">=</span> <span class="token constant">QUEUE_STATUS</span><span class="token punctuation">.</span><span class="token constant">SHUTDOWN</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
  <span class="token comment">// 任务管理器工作</span>
  <span class="token keyword">private</span> <span class="token function">work</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>isWorking <span class="token operator">&amp;&amp;</span> hasNextTask<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 如果有会继续执行下一个任务</span>
      <span class="token comment">// 直到任务管理器被暂停、或者任务队列为空</span>
      <span class="token function">runNextTask</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这里面比较关键的点有两个：</p> <ol><li>暂停任务管理器的时候，需要考虑如何处理正在运行的任务。</li> <li>执行任务的时候，需要进行一些异常处理。同时，任务的运行可能会进行分裂并产生新的任务，需要对新任务进行处理。</li></ol> <h3 id="暂停与恢复"><a href="#暂停与恢复" class="header-anchor">#</a> 暂停与恢复</h3> <p>我们先来看第一点：任务管理器暂停和恢复时的处理。</p> <p>一个简单粗暴的处理方式是，将当前正在运行的任务继续运行完成。但这种处理方式，与我们对于暂停的理解有一些误差。因此，我们可以考虑让任务本身支持重置的功能，比如运行过程中判断任务状态是否需要继续执行，结合销毁当前任务、并将原有任务进行重置。</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">abstract</span> <span class="token keyword">class</span> <span class="token class-name">CommonTask</span> <span class="token punctuation">{</span>
  <span class="token comment">/** 重置任务 **/</span>
  <span class="token comment">// 会返回任务本身，该任务应该是被重置过的最初状态</span>
  <span class="token keyword">abstract</span> <span class="token function">reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">:</span> CommonTask<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>实现起来其实也不会很难：</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">class</span> <span class="token class-name">ATask</span> <span class="token keyword">extends</span> <span class="token class-name">CommonTask</span> <span class="token punctuation">{</span>
  <span class="token keyword">public</span> <span class="token function">reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 销毁当前任务</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">destroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 并返回一个重置后的新任务</span>
    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ATask</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>对于任务管理器来说，要做的事情也比较简单了：暂停任务管理器的时候，将当前任务重置、并扔回任务队列的头部。</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">class</span> <span class="token class-name">TaskManager</span> <span class="token punctuation">{</span>
  <span class="token comment">// 暂停任务管理器</span>
  <span class="token keyword">public</span> <span class="token function">pause</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>status <span class="token operator">=</span> <span class="token constant">QUEUE_STATUS</span><span class="token punctuation">.</span><span class="token constant">PAUSE</span><span class="token punctuation">;</span>
    <span class="token comment">// 将当前任务重置，并扔回任务队列头部</span>
    taskList<span class="token punctuation">.</span><span class="token function">unshift</span><span class="token punctuation">(</span>currentTask<span class="token punctuation">.</span><span class="token function">reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><h3 id="任务管理器工作"><a href="#任务管理器工作" class="header-anchor">#</a> 任务管理器工作</h3> <p>任务管理器工作的时候，主要工作内容包括依次运行任务、处理任务异常、处理任务运行后分裂产生的新任务。</p> <div class="language-ts extra-class"><pre class="language-ts"><code><span class="token keyword">class</span> <span class="token class-name">TaskManager</span> <span class="token punctuation">{</span>
  <span class="token comment">// 任务管理器工作</span>
  <span class="token keyword">private</span> <span class="token keyword">async</span> <span class="token function">work</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>isWorking <span class="token operator">&amp;&amp;</span> hasNextTask<span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token comment">// 如果满足条件，会继续执行下一个任务</span>
      currentTask <span class="token operator">=</span> <span class="token function">getNextTask</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">const</span> resultTask <span class="token operator">=</span> <span class="token keyword">await</span> currentTask<span class="token punctuation">.</span><span class="token function">execute</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">catch</span><span class="token punctuation">(</span><span class="token punctuation">(</span>error<span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
        <span class="token comment">// 异常处理</span>
      <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token comment">// 判断是否有分裂的新任务</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>resultTask<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 如果有，就塞回到任务队列的头部，需要优先处理</span>
        taskList<span class="token punctuation">.</span><span class="token function">unshift</span><span class="token punctuation">(</span>resultTask<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token comment">// 继续执行下一个任务</span>
      <span class="token function">checkContinueWork</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>以上大概是我们在设计一个任务管理器的过程中，需要进行思考的一些问题、和简单的实现方式。除此之外，在一个更加复杂的应用场景下，我们还可能会遇到多个任务队列的管理和资源调度、同步任务和异步任务的管理、任务支持优先级设置等各式各样的功能设计。</p> <h2 id="结束语"><a href="#结束语" class="header-anchor">#</a> 结束语</h2> <p>任务管理也好、队列/堆栈的设计也好，都会在工程中经常遇到。而随着应用场景的不一样，我们的设计并不能简单地进行复用，每一次都可以结合业务本身、工程本身而设计出更加合适的调整，每一次我们也都可以给自己提出不一样的要求。</p></div> <!----> <footer class="page-edit"><div class="edit-link"><a href="https://github.com/godbasin/front-end-playground/edit/sourcecode/docs/front-end-basic/deep-learning/task-runner-design.md" target="_blank" rel="noopener noreferrer">帮阿猪改善此页面！</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <!----> <blockquote>部分文章中使用了一些网站的截图，如果涉及侵权，请告诉我删一下谢谢~</blockquote> <div style="margin-top:30px;"><div class="el-row" style="margin-left:-10px;margin-right:-10px;"><div class="el-col el-col-24 el-col-sm-0 el-col-md-2 el-col-lg-4" style="padding-left:10px;padding-right:10px;display:block;"><div style="width:1px;height:1px;"></div></div> <div class="el-col el-col-24 el-col-sm-24 el-col-md-18 el-col-lg-16" style="padding-left:10px;padding-right:10px;"><div class="el-card box-card is-always-shadow"><div class="el-card__header"><div class="clearfix"><span>温馨提示喵</span></div></div><div class="el-card__body"> <div class="el-row" style="margin-left:-10px;margin-right:-10px;"><div class="el-col el-col-24 el-col-xs-24 el-col-sm-12" style="padding-left:10px;padding-right:10px;"><div class="el-image"><div class="image-slot"><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/assets/img/loading.gif" style="width:100%;"></div><!----></div></div> <div class="el-col el-col-24 el-col-xs-24 el-col-sm-12" style="padding-left:10px;padding-right:10px;"><div class="copyright-text"><div>本文版权归作者所有，欢迎转载，但未经作者同意必须保留此段声明，且在文章页面明显位置给出原文连接，否则保留追究法律责任的权利。</div> <div>出处：被删的前端游乐场</div> <div>作者：<a href="https://github.com/godbasin" target="_blank">被删</a></div></div></div></div></div></div></div></div></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
        ←
        <a href="/front-end-playground/front-end-basic/deep-learning/why-spreadsheet-app-excited.html" class="prev">
          在线Excel项目到底有多刺激
        </a></span> <span class="next"><a href="/front-end-playground/front-end-basic/deep-learning/network-design-responsibility-driven-design.html">
          在线文档的网络层开发思考--职责驱动设计
        </a>
        →
      </span></p></div>  <div class="gitalk-container theme-default-content"><div id="gitalk-container" class="content"></div></div></main> <div id="kitty-container"><span><div role="tooltip" id="el-popover-9485" aria-hidden="true" class="el-popover el-popper" style="width:undefinedpx;display:none;"><!----><img src="https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/2code2.jpg" class="image"> <div class="text">牡羊猪的猫粮罐</div> </div><span class="el-popover__reference-wrapper"><div id="kitty" style="background:url(https://github-imglib-1255459943.cos.ap-chengdu.myqcloud.com/assets/img/kitty0.svg);"></div></span></span> <div class="el-dialog__wrapper" style="display:none;"><div role="dialog" aria-modal="true" aria-label="牡羊猪是这样渐渐胖成猪的喵（点击图片可以切换噢）" class="el-dialog" style="margin-top:15vh;"><div class="el-dialog__header"><span class="el-dialog__title">牡羊猪是这样渐渐胖成猪的喵（点击图片可以切换噢）</span><button type="button" aria-label="Close" class="el-dialog__headerbtn"><i class="el-dialog__close el-icon el-icon-close"></i></button></div><!----><!----></div></div></div></div><div class="global-ui"></div></div>
    <script src="/front-end-playground/assets/js/app.1e2670bf.js" defer></script><script src="/front-end-playground/assets/js/2.38d016d1.js" defer></script><script src="/front-end-playground/assets/js/3.e3f029cb.js" defer></script><script src="/front-end-playground/assets/js/36.be11f947.js" defer></script>
  </body>
</html>
